package com.skynet.whwpro.Alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAppQrcodeCreateRequest;
import com.alipay.api.response.AlipayOpenAppQrcodeCreateResponse;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

import com.skynet.whwpro.bean.BeanJyjlb;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CrossOriginFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@At("/ewm")
@IocBean
@Filters(@By(type = CrossOriginFilter.class))
public class CreateService {
    private static final Logger logger = LoggerFactory.getLogger(CreateService.class);
    private String rooturl = "https://mb.ynhotel.net/";
    @Inject
    private Dao dao;

    @Inject
    private AlipayClient alipayClient;

    @At("/addmember")
    @Ok("json")
    public Object addmember(@Param("sjid") String sjid) {
        String url = "pages/confirmSellers/main?";
        Map<String, String> rd = new HashMap<>();
        rd.put("sjid", sjid);
        String des = "邀请员工加入商户";
        return alipayOpenAppQrcodeCreateService(url, rd, des);
    }

    @At
    @Ok("json")
    public Object paySellers(@Param("json") String json, @Param("userId") String userId) {
        String url = "pages/tradView/main?";
        Map<String, String> rd = Json.fromJson(Map.class, json);
        BeanJyjlb bean = new BeanJyjlb();
        String wyid = UUID.randomUUID().toString().replaceAll("-", "");
        bean.setWyid(wyid);
        bean.setXsdid(rd.get("sjid"));
        rd.put("ddid", wyid);
        bean.setZt("0");
        dao.insert(bean);
        String des = "生成用户交易订单 ";
        return alipayOpenAppQrcodeCreateService(url, rd, des);
    }



    //扫码订单
    @At
    @Ok("json")
    public Object paySellers2(@Param("json") String json, @Param("userId") String userId) {
        String url = "pages/tradView/main?";
        Map<String, String> rd = Json.fromJson(Map.class, json);
        BeanJyjlb bean = new BeanJyjlb();
        String wyid = UUID.randomUUID().toString().replaceAll("-", "");
        bean.setWyid(wyid);
        bean.setXsdid(rd.get("sjid"));
        rd.put("ddid", wyid);
        bean.setZt("0");
        dao.insert(bean);
        String des = "生成用户交易订单 ";
        return alipayOpenAppQrcodeCreateService(url, rd, des);
    }

    //格式转换为支付宝能识别的
    private String RecordFormat(Map<String, String> rd) {
        List<String> sb = new ArrayList<>();
        for (Map.Entry<String, String> entry : rd.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            sb.add(mapKey + "=" + mapValue);
        }
        return StringUtils.join(sb, "&");
    }


    public Object alipayOpenAppQrcodeCreateService(String url, Map<String, String> param, String des) {
        AlipayOpenAppQrcodeCreateRequest alipayRequest = new AlipayOpenAppQrcodeCreateRequest();
        //请确认是否在工程中引入了fastjson
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("url_param", url + this.RecordFormat(param));
        params.put("query_param", this.RecordFormat(param));
        params.put("describe", des);
        //设置业务参数，bizContent为发送的请求信息，开发者需要根据实际情况填充此类
        Object obj = JSONObject.toJSON(params);
        alipayRequest.setBizContent(obj.toString());
        //sdk请求客户端，已将配置信息初始化
        AlipayOpenAppQrcodeCreateResponse alipayResponse = null;
        try {
            //因为是接口服务，使用exexcute方法获取到返回值
            alipayResponse = alipayClient.execute(alipayRequest);
            if (alipayResponse.isSuccess()) {
                logger.info("调用成功");
                //TODO 实际业务处理，开发者编写。可以通过alipayResponse.getXXX的形式获取到返回值
            } else {
                logger.info("调用失败");
            }
            return alipayResponse;
        } catch (AlipayApiException e) {
            if (e.getCause() instanceof java.security.spec.InvalidKeySpecException) {
                return "商户私钥格式不正确，请确认配置文件alipay_openapi_sanbox.properties中是否配置正确";
            }
        }
        return alipayResponse;
    }

    public static AlipayClient getAlipayClient() {
        ResourceBundle bundle = ResourceBundle.getBundle("alipay_openapi_sanbox");
        // 网关
        String URL = bundle.getString("ALIPAY_GATEWAY_URL");
        // 商户APP_ID
        String APP_ID = bundle.getString("APP_ID");
        // 商户RSA 私钥
        String APP_PRIVATE_KEY = bundle.getString("RSA2_PRIVATE_KEY");
        // 请求方式 json
        String FORMAT = bundle.getString("FORMAT");
        // 编码格式，目前只支持UTF-8
        String CHARSET = bundle.getString("CHARSET");
        // 支付宝公钥
        String ALIPAY_PUBLIC_KEY = bundle.getString("ALIPAY_RSA2_PUBLIC_KEY");
        // 签名方式
        String SIGN_TYPE = bundle.getString("SIGN_TYPE");
        return new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
    }
}